package ch.exploadingelephants.graph;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Sandro De Zanet
 * 
 */
public class DotString implements Iterable<DotColor> {

    private final List<DotColor> string;

    /**
     * empty constructor
     */
    public DotString() {
	string = new LinkedList<DotColor>();
    }

    /**
     * @param pattern
     */
    public DotString(String pattern) {
	this.string = new LinkedList<DotColor>();
	for (int i = 0; i < pattern.length(); i++) {
	    DotColor candidate = DotColor.parse(pattern.charAt(i));
	    if (candidate != null) {
		string.add(candidate);
	    }
	}
    }

    /**
     * @param newString
     */
    public DotString(List<DotColor> newString) {
	this.string = newString;
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Iterable#iterator()
     */
    public Iterator<DotColor> iterator() {
	return string.iterator();
    }

    public DotColor next() {
	if (string.isEmpty()) {
	    return null;
	}
	return string.get(0);
    }

    public DotString consumate() {
	List<DotColor> newString = new LinkedList<DotColor>();
	newString.addAll(this.string);
	if (!newString.isEmpty()) {
	    newString.remove(0);
	}
	return new DotString(newString);
    }

    /**
     * @return
     */
    public DotString copy() {
	List<DotColor> result = new LinkedList<DotColor>();
	result.addAll(this.string);
	return new DotString(result);
    }

    /**
     * @param color
     */
    public void append(DotColor color) {
	this.string.add(color);
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
	String result = "";
	for (DotColor color : string) {
	    result += color.getCharacter();
	}
	return result;
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
	return string.hashCode();
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Object#equals(java.lang.Object)
     */
    @Override
    public boolean equals(Object o) {
	if (o != null) {
	    if (o instanceof DotString) {
		DotString other = (DotString) o;
		return string.equals(other.string);
	    }
	}
	return false;
    }

    /**
     * @return number of dots
     */
    public int size() {
	return string.size();
    }
}
